package com.hup.timer.service.gesture;

import com.hup.timer.constant.TimerConstant;
import com.hup.timer.service.gesture.TimerWindowGesture.GestureCallback;
import com.hup.utils.commons.hardware.MouseLooper;
import com.hup.utils.commons.hardware.MouseLooper.MlPermitCallback;
import com.hup.utils.swing.FrameUtil;
import lombok.extern.log4j.Log4j2;

import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * @author hugan
 * @date 2020/4/6
 */
@Log4j2
public class SetAlphaListener extends MouseAdapter implements MlPermitCallback {

    private final Window win;
    private final GestureCallback callback;
    private final MouseLooper mouseLooper;

    /**
     * 是否有改变过
     */
    private boolean hadChanged;
    private float alpha0;
    private float lastAlpha;
    /**
     * 调节时,是否已经到达了上下界
     */
    private boolean touchMin, touchMax;

    public SetAlphaListener(GestureCallback callback) {
        this.win = callback.getWindow();
        this.callback = callback;
        mouseLooper = new MouseLooper(this);
    }

    @Override
    public void mousePressed(MouseEvent e) {
        alpha0 = callback.getAlpha();
        log.info("激活设置alpha, alpha0={}", alpha0);
        touchMin = touchMax = false;
        mouseLooper.mousePressed(e);
    }

    @Override
    public boolean canLoop(boolean isLoopY, boolean isDown) {
        return !((isDown && touchMin) || (!isDown && touchMax));
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        int yDiff = mouseLooper.mouseDraggedY(e);
        lastAlpha = alpha0 + (-yDiff / 88f);
        //log.info("lastAlpha={}", lastAlpha);

        touchMin = touchMax = false;
        if (lastAlpha > TimerConstant.ALPHA_MAX) {
            lastAlpha = TimerConstant.ALPHA_MAX;
            touchMax = true;
        } else if (lastAlpha < TimerConstant.ALPHA_MIN) {
            lastAlpha = TimerConstant.ALPHA_MIN;
            touchMin = true;
        }
        FrameUtil.setAlpha(win, lastAlpha);
        hadChanged = true;
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        if (hadChanged) {
            callback.afterChangedAlpha(lastAlpha);
            hadChanged = false;
        }
    }

}
